/**
 * 基于vue 指令数据验证
 * 验证 1.数据类型 2.支持正则 3.数据范围
 */
import Vue from 'vue'
const REGEX = [
    {name:'phone',regx:/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/}, //手机号
    {name:'idcard',regx:/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/},           //身份证
    {name:'email',regx:/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/}, //email
  ]
  Vue.directive('checkParam', {
    inserted: function (el, binding, vNode) {
      el.addEventListener('keyup', function (event) {
          let requiredMsg = binding.value.requiredMsg; //非空判断
          let dataType = binding.value.dataType //数据类型 姓名，身份证，手机号码,邮箱，
          let regexMsg = binding.value.regexMsg //数据类型 提示正则
          let minMaxMsg = binding.value.minMaxMsg //数据范围 提示
          let regex = binding.value.regex;  //自定义正则
          let minMax = binding.value.minMax;  //数据范围
           el.setAttribute('error-msg','')
          if(requiredMsg){
            if (!el.value || el.value === '') {
              el.setAttribute('error-msg',requiredMsg)
              return;
            }
          }
          if(regex){  //自定义正则校验
            let mREGEX = REGEX.filter(u=>u.name == regex) //判断是否 是自定义数据类型
            if(mREGEX[0]){
                regex = mREGEX[0].regx
            }
            if (!el.value.match(regex)) {
                el.setAttribute('error-msg',regexMsg);
                return;
            }
          }
          //console.log("====")
          if(minMax){
            let tmp = minMax.split('~');
            console.log(tmp)
            let min = tmp[0];
            let max = tmp[1];
            if(min&&max){ //范围

            }
            if(min){
                if(parseInt(min)>parseInt(el.value)){
                  el.setAttribute('error-msg',minMaxMsg);
                return;
              }
            }
            if(max){
                if(parseInt(el.value)>parseInt(max)){
                  el.setAttribute('error-msg',minMaxMsg);
                  return;
                }
            }
          }
      })
    }
  });
  Vue.directive('checkSubmit', {
    inserted: function (el, binding, vNode) {
      el.addEventListener('click', function (event) {
          let eles = document.getElementsByTagName('input');
          var evObj = document.createEvent('Event')
          evObj.initEvent('keyup', true, true)
          for(let key in eles){
             if(key>=0){
                eles[key].dispatchEvent(evObj)
             }
            }
          for(let key in eles){
            if(key>=0){
              let errorMsg = eles[key].getAttribute('error-msg');
              if(errorMsg){
                alert(errorMsg)
                return;
                console.log(key+"errorMsg==>"+errorMsg)
              }
            }
          }
          vNode.context.submit();
      })
    }
  });